package mongodb

import (
	"context"
	"fmt"
	"go-gin-api/core/config"
	"go-gin-api/core/log"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.uber.org/zap"
)

var Mongo *mongo.Client

func Init() {
	param := fmt.Sprintf(fmt.Sprintf("mongodb://%s:%s", config.GetString("mongodb.host"), config.GetString("mongodb.port")))
	clientOptions := options.Client().ApplyURI(param)

	// 建立客户端连接
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Error().Error("mongodb conn err", zap.Error(err))
		fmt.Println(err)
	}
	// 检查连接情况
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		log.Error().Error("mongodb conn err", zap.Error(err))
		fmt.Println(err)
	}

	Mongo = client
}
